package top.yangbuyi.config.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yangbuyi.domain.User;
import top.yangbuyi.service.impl.UserService;
import top.yangbuyi.vo.ActiverUser;

/**
 * @description: 杨不易网站:www.yangbuyi.top
 * @program: yangbuyiopenHis2020
 * @ClassName: UserRealm
 * @create: 2020-08-28 00:15
 * @author: yangbuyi
 * @since： JDK1.8
 * @UserRealm: 自定义Realm匹配用户名和密码$
 **/

@Slf4j
public class UserRealm extends AuthorizingRealm {

	  @Autowired
	  @Lazy
	  private UserService userService;

	  @Override
	  public String getName() {
			return this.getClass().getSimpleName();
	  }

	  /**
	   * 认证 -- 登录
	   *
	   * @param authenticationToken
	   * @return
	   * @throws AuthenticationException
	   */
	  @Override
	  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
			log.info("登录认证开始");
	  	  	// 1.得到用户名
			String phone = (String) authenticationToken.getPrincipal();
			// 2.根据电话查询用户是否存在
			User user = userService.queryUserByPhone(phone);
			// 3.判断用户是否存在
			if (null != user) {
				  // 4.根据用户id 查询 用户角色
				  // 5.根据用户id查询权限
				  // 6.组装数据
				  ActiverUser activerUser = new ActiverUser();
				  activerUser.setUser(user);
				  SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
						  activerUser, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName()
				  );

				  log.info("登录认证成功:{}"+ info);
				  log.info("登录认证成功:{}"+ activerUser);
				  return info;
			}
			log.info("登录认证失败:{用户不存在}");
			return null;
	  }

	  /**
	   * 授权 -- 登录之后判断某个用户是否拥有某个菜单和按钮的权限
	   *
	   * @param principalCollection
	   * @return
	   */
	  @Override
	  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
			// 获取角色权限
			ActiverUser activerUser = (ActiverUser) principalCollection.getPrimaryPrincipal();
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			return info;
	  }


}
